package vn.com.vega.music.view.custom;

import java.lang.ref.WeakReference;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.ActivityBase;
import vn.com.vega.chacha.v2.Appinstant;
import vn.com.vega.chacha.v2.PlayerScreen;
import vn.com.vega.chacha.v2.player.PlayerService;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.utils.AnimationChaCha;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.CurrentPlaylistAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class BottomPlayerView extends FrameLayout implements
		OnSeekBarChangeListener, View.OnClickListener {
	private Context mContext;
	private ImageView mThumb;
	private SeekBar mProgressbar;
	private ImageButton mPlayPauseBtn;
	private TextView mCurrentTime;
	private TextView mTotalTime;
	private ImageButton mNextBtn;
	private ImageButton mListSongBtn;
	private TextView mSongTitle;
	private LinearLayout mLayoutPlaypause;
	private Song mSong;
	public View mLayoutListPlay;
	private ListView mListSongCurrentPlay;
	private TextView mPlaylistTitle;
	private ProgressBar mLoadingSongProgress;
	private ImageButton mShowPlayerBtn;
	private ShowHideBottomPlayerListener showHidePlayerListener;
	private IntentFilter mIntentFilter;

	public BottomPlayerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		init(context);
	}

	public BottomPlayerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		init(context);
	}

	public BottomPlayerView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		init(context);
	}

	private void init(Context ctx) {
		mContext = ctx;
		LayoutInflater inflater = (LayoutInflater) ctx
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		FrameLayout frameLayout = (FrameLayout) inflater.inflate(
				R.layout.view_player_bottom, this);
		mThumb = (ImageView) frameLayout.findViewById(R.id.imv_songthumb);
		mProgressbar = (SeekBar) frameLayout.findViewById(R.id.seekbar);
		mPlayPauseBtn = (ImageButton) frameLayout
				.findViewById(R.id.bt_pause_play);
		mCurrentTime = (TextView) frameLayout
				.findViewById(R.id.tv_current_time);
		mTotalTime = (TextView) frameLayout.findViewById(R.id.tv_duration);

		mNextBtn = (ImageButton) frameLayout.findViewById(R.id.bt_next);
		mListSongBtn = (ImageButton) frameLayout
				.findViewById(R.id.bt_list_song);
		mListSongBtn.setOnClickListener(this);
		mSongTitle = (TextView) frameLayout.findViewById(R.id.tv_songtitle);
		mSongTitle.setSelected(true);
		mLayoutPlaypause = (LinearLayout) frameLayout
				.findViewById(R.id.layout_play_pause);
		mThumb.setOnClickListener(this);

		mNextBtn.setOnClickListener(this);
		mPlayPauseBtn.setOnClickListener(this);
		mLayoutPlaypause.setOnClickListener(this);
		mProgressbar.setOnSeekBarChangeListener(this);
		mLayoutListPlay = frameLayout
				.findViewById(R.id.layout_background_playlist);
		mLayoutListPlay.setOnClickListener(this);

		mListSongCurrentPlay = (ListView) frameLayout
				.findViewById(R.id.lv_list_song_current_play);
		mPlaylistTitle = (TextView) frameLayout
				.findViewById(R.id.tv_playlist_title);
		mLoadingSongProgress = (ProgressBar) frameLayout
				.findViewById(R.id.progress_loading_song);
		mShowPlayerBtn = (ImageButton) frameLayout
				.findViewById(R.id.bt_show_bottom_player);
		mShowPlayerBtn.setOnClickListener(this);

		mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(PlayerService.PLAYSTATE_CHANGED);
		mIntentFilter.addAction(PlayerService.SONG_END);
		mIntentFilter.addAction(PlayerService.SONG_ERROR);
		mIntentFilter.addAction(PlayerService.SONG_PREPARING);
	}

	public void setShowHideListener(
			ShowHideBottomPlayerListener showHideBottomPlayerListener) {
		showHidePlayerListener = showHideBottomPlayerListener;
	}

	public BroadcastReceiver playerBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (PlayerService.SONG_PREPARING.equalsIgnoreCase(action)) {
				// is preparing song
				showPlayer(true);
				Log.e(BottomPlayerView.class.getSimpleName(),
						"is preparing song for play");
				if (!Util.playerIsInit()) {
					mPlayPauseBtn.setVisibility(View.GONE);
					mLoadingSongProgress.setVisibility(View.VISIBLE);
				}
			} else if (PlayerService.PLAYSTATE_CHANGED.equalsIgnoreCase(action)) {
				if (!Util.playerIsInit()) {
					// Player not init here
					return;
				}
				mLoadingSongProgress.setVisibility(View.GONE);
				mPlayPauseBtn.setVisibility(View.VISIBLE);
				updateInfo();
				if (Util.isPlaying()) {
					showPlayer(true);
					handler.sendEmptyMessage(UPDATE_PROGRESS);
				} else {
					handler.removeMessages(UPDATE_PROGRESS);
				}
			} else if (PlayerService.SONG_END.equalsIgnoreCase(action)) {
				// Play done a song
				handler.removeMessages(UPDATE_PROGRESS);
			} else if (PlayerService.SONG_ERROR.equalsIgnoreCase(action)) {
				// have error while play one song
				handler.removeMessages(UPDATE_PROGRESS);
			}
		}
	};

	public static final int HIDE_PLAYER = 0;
	public static final int UPDATE_PROGRESS = 1;
	public static final int TIME_DELAY = 5000;

	private BottomPlayerHandler handler = new BottomPlayerHandler(this);

	static class BottomPlayerHandler extends Handler {
		WeakReference<BottomPlayerView> bottomPlayerRfc;

		public BottomPlayerHandler(BottomPlayerView bottomPlayerView) {
			bottomPlayerRfc = new WeakReference<BottomPlayerView>(
					bottomPlayerView);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			BottomPlayerView bottomPlayerView = bottomPlayerRfc.get();
			if (bottomPlayerView == null) {
				return;
			}
			if (bottomPlayerView.mContext instanceof ActivityBase) {
				ActivityBase act = (ActivityBase) bottomPlayerView.mContext;
				if (act == null || act.isDestroy) {
					return;
				}
			}
			switch (msg.what) {
			case UPDATE_PROGRESS:
				bottomPlayerView.updateProgress();
				sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000);
				break;
			case HIDE_PLAYER:
				if (bottomPlayerView.mLayoutListPlay.isShown()) {
					removeMessages(HIDE_PLAYER);
					sendEmptyMessageDelayed(HIDE_PLAYER, TIME_DELAY);
					return;
				}
				bottomPlayerView.showPlayer(false);
				break;

			default:
				break;
			}

		}

	}

	public void showPlayer(boolean show) {
		if (show) {
			if (!mLayoutPlaypause.isShown()) {
				// mLayoutPlaypause.startAnimation(AnimationChaCha
				// .infFromBottom(200));
				mLayoutPlaypause.setVisibility(View.VISIBLE);
				mShowPlayerBtn.setVisibility(View.GONE);
				mLayoutListPlay.setVisibility(View.GONE);
				if (showHidePlayerListener != null) {
					showHidePlayerListener.onShowBottomPlayer();
				}
				handler.sendEmptyMessageDelayed(HIDE_PLAYER, TIME_DELAY);
			}
		} else {
			if (mLayoutPlaypause.isShown()) {
				// mLayoutPlaypause.startAnimation(AnimationChaCha
				// .outToBottom(200));
				mLayoutPlaypause.setVisibility(View.GONE);
				mShowPlayerBtn.setVisibility(View.VISIBLE);
				mLayoutListPlay.setVisibility(View.GONE);
				if (showHidePlayerListener != null) {
					showHidePlayerListener.onHideBottomPlayer();
				}
			}
		}
	}

	public boolean playerIsShow() {
		return mLayoutPlaypause.isShown();
	}

	private void updateInfo() {
		handler.removeMessages(HIDE_PLAYER);
		handler.sendEmptyMessageDelayed(HIDE_PLAYER, TIME_DELAY);
		Song song = Util.getCurrentSongPlay();
		if (song != null) {
			if (song != this.mSong) {
				((Appinstant) mContext.getApplicationContext()).mImageLoader
						.download(song.imageUrl, mThumb);
				mSongTitle.setText(song.title);
				mTotalTime.setText(Util.intToStringTimeFormat(Util
						.getTotalTime()));
				mSong = song;
			}
			mCurrentTime.setText(Util.intToStringTimeFormat(Util
					.getCurrentTime()));
			mProgressbar.setMax(Util.getTotalTime());
			if (Util.isPlaying()) {
				mPlayPauseBtn.setSelected(false);
			} else {
				mPlayPauseBtn.setSelected(true);
			}
		}
	}

	public void updateProgress() {
		int currentTime = Util.getCurrentTime();
		mProgressbar.setProgress(currentTime);
		mCurrentTime.setText(Util.intToStringTimeFormat(currentTime));
	}

	private void showListSong() {
		List<Song> listSongPlay = Util.getListSongPlay();
		if (listSongPlay != null && listSongPlay.size() > 0) {
			int indextCurrentSong = Util.getIndexCurrentSongPlay();
			CurrentPlaylistAdapter apdapter = new CurrentPlaylistAdapter(
					listSongPlay, indextCurrentSong, mContext);
			mListSongCurrentPlay.setAdapter(apdapter);
			mPlaylistTitle.setText(String.format(
					mContext.getString(R.string.current_playlist_title),
					listSongPlay.size()));
			mLayoutListPlay.startAnimation(AnimationChaCha.infFromBottom(200));
			mLayoutListPlay.setVisibility(View.VISIBLE);
			mListSongCurrentPlay
					.setOnItemClickListener(new AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							// TODO Auto-generated method stub
							hideListSong();
							Util.openSongAtPosition(arg2);
						}
					});
		}
	}

	public void hideListSong() {
		if (mLayoutListPlay.isShown()) {
			mLayoutListPlay.startAnimation(AnimationChaCha.outToBottom(200));
			mLayoutListPlay.setVisibility(View.GONE);
		}
	}

	private void goToPlayerScreen() {
		Intent intent = new Intent(mContext, PlayerScreen.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		mContext.startActivity(intent);
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		if (fromUser) {
			Util.seek(progress);
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		handler.removeMessages(HIDE_PLAYER);
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		handler.sendEmptyMessageDelayed(HIDE_PLAYER, TIME_DELAY);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		handler.removeMessages(HIDE_PLAYER);
		handler.sendEmptyMessageDelayed(HIDE_PLAYER, TIME_DELAY);
		if (v.getId() != R.id.bt_list_song) {
			hideListSong();
		}
		switch (v.getId()) {
		case R.id.bt_list_song:
			if (mLayoutListPlay.isShown()) {
				hideListSong();
			} else {
				showListSong();
			}
			break;
		case R.id.imv_songthumb:
			if (Util.isPlaying()) {
				goToPlayerScreen();
			}
			break;
		case R.id.bt_next:
			Util.next();
			break;
		case R.id.layout_play_pause:
		case R.id.bt_pause_play:
			if (Util.isPlaying()) {
				Util.pause();
				mPlayPauseBtn.setSelected(true);
			} else {
				Util.play();
				mPlayPauseBtn.setSelected(false);
			}
			break;
		case R.id.bt_show_bottom_player:
			showPlayer(true);

		default:
			break;
		}
	}

	public ImageView getSongThumb() {
		return mThumb;
	}

	public void startUpdate() {
		mContext.registerReceiver(playerBroadcastReceiver, mIntentFilter);
		if (Util.isPlaying()) {
			handler.sendEmptyMessage(UPDATE_PROGRESS);
			handler.sendEmptyMessageDelayed(HIDE_PLAYER, TIME_DELAY);
		}
	}

	public void stopUpdate() {
		handler.removeCallbacksAndMessages(null);
		try {
			mContext.unregisterReceiver(playerBroadcastReceiver);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public interface ShowHideBottomPlayerListener {
		public void onShowBottomPlayer();

		public void onHideBottomPlayer();
	}
}
